package com.leo.boot.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;

import javax.script.ScriptEngine;
import javax.script.SimpleBindings;

import static cn.hutool.core.bean.BeanUtil.beanToMap;

@Slf4j
@UtilityClass
public class CalculationUtils {

    private static final ScriptEngine ENGINE = new GroovyScriptEngineFactory().getScriptEngine();

    @SuppressWarnings("unchecked")
    public static <T> T eval(String formula, Object param) {
        try {
            return (T) ENGINE.eval(formula, new SimpleBindings(beanToMap(param)));
        } catch (Exception e) {
            log.error("calculate error", e);
        }
        return null;
    }
}
